package com.wang.jmonkey.modules.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.jmonkey.modules.system.mapper.SystemDaclMapper;
import com.wang.jmonkey.modules.system.model.entity.SystemDaclEntity;
import com.wang.jmonkey.modules.system.model.enums.SystemDaclPrincipalTypeEnum;
import com.wang.jmonkey.modules.system.model.param.SystemUserParam;
import com.wang.jmonkey.modules.system.service.SystemDaclService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

/**
 * 数据权限信息(SystemDacl)表服务实现类
 *
 * @author HeJiawang
 * @since 2021-05-14 16:12:41
 */
@Service
public class SystemDaclServiceImpl extends ServiceImpl<SystemDaclMapper, SystemDaclEntity> implements SystemDaclService {

    /**
     * mapper
     */
    @Autowired
    private SystemDaclMapper mapper;

    /**
     * 删除用户数据权限信息
     * @param userId 用户id
     * @return true 删除成功
     */
    @Override
    public boolean deleteByUserId(Serializable userId) {
        return mapper.deleteByUserId(userId) >= 0;
    }

    /**
     * 更新用户数据权限信息
     * @param user 用户信息
     * @return true 维护更新成功
     */
    @Transactional
    @Override
    public boolean refreshDacl(SystemUserParam user) {
        boolean result = mapper.deleteByUserId(user.getId()) >= 0;

        List<SystemDaclEntity> daclList = CollUtil.newArrayList();
        daclList.addAll(this.daclBuild(user.getId(), SystemDaclPrincipalTypeEnum.ROLE, user.getRoleIdList()));
        daclList.addAll(this.daclBuild(user.getId(), SystemDaclPrincipalTypeEnum.DEPT, user.getDeptIdList()));
        daclList.addAll(this.daclBuild(user.getId(), SystemDaclPrincipalTypeEnum.DUTY, user.getDutyIdList()));
        daclList.addAll(this.daclBuild(user.getId(), SystemDaclPrincipalTypeEnum.JOB, user.getJobIdList()));

        return result && super.saveBatch(daclList);
    }

    private List<SystemDaclEntity> daclBuild(Long userId, SystemDaclPrincipalTypeEnum type, List<Long> principalIdList) {
        List<SystemDaclEntity> result = CollUtil.newArrayList();

        if (CollUtil.isEmpty(principalIdList)) return result;

        principalIdList.forEach(principalId -> {

            SystemDaclEntity dacl = new SystemDaclEntity()
                    .setPrincipalType(type)
                    .setPrincipalId(principalId)
                    .setUserId(userId);
            result.add(dacl);
        });

        return result;
    }

    /**
     * 删除数据权限信息与用户关联关系
     * @param principalId 数据主体id
     * @param type 数据类型
     * @return true 删除成功
     */
    @Override
    public boolean deleteByPrincipalId(Serializable principalId, SystemDaclPrincipalTypeEnum type) {
        return mapper.deleteByPrincipalId(principalId, type) >= 0;
    }
}
